package com.atguigu.champter8;

import com.atguigu.beans.HotItem;
import com.atguigu.beans.UserBehavior;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Comparator;
import java.util.TreeSet;


//每隔5分钟输出最近一小时内点击量最多的3件商品
public class Flink04_Project_High_TopN_1 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 9999);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .readTextFile("datas/input/UserBehavior.csv")
                .map(line -> {
                    String[] data = line.split(",");
                    return new UserBehavior(Long.valueOf(data[0]),
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2]),
                            data[3],
                            Long.parseLong(data[4]) * 1000);
                })
//                .filter(ub -> "pv".equals(ub.getBehavior()))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((event, timestamp) -> event.getTimestamp())
                )
                .keyBy(UserBehavior::getItemId)
                .window(SlidingEventTimeWindows.of(Time.hours(3), Time.minutes(60)))
                .aggregate(new AggregateFunction<UserBehavior, Long, Long>() {
                               @Override
                               public Long createAccumulator() {
                                   return 0L;
                               }

                               @Override
                               public Long add(UserBehavior value, Long acc) {
                                   return ++acc;
                               }

                               @Override
                               public Long getResult(Long acc) {
                                   return acc;
                               }

                               @Override
                               public Long merge(Long a, Long b) {
                                   return a + b;
                               }
                           },
                        new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                            @Override
                            public void process(Long key,
                                                Context ctx,
                                                Iterable<Long> elements,
                                                Collector<HotItem> out) throws Exception {
                                long end = ctx.window().getEnd();
                                out.collect(new HotItem(key, elements.iterator().next(), end));
                            }
                        })
                //求点击量的top3
                //同一个窗口的进行比较
                .keyBy(HotItem::getWindowEndTime)
                .process(new KeyedProcessFunction<Long, HotItem, String>() {

//                    private TreeSet<HotItem> set;
                    private ValueState<TreeSet<HotItem>> top3Plus;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        top3Plus = getRuntimeContext().getState(new ValueStateDescriptor<TreeSet<HotItem>>("top3Plus", TypeInformation.of(new TypeHint<TreeSet<HotItem>>() {
                        })));
                    }

                    @Override
                    public void processElement(HotItem value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        if (top3Plus.value() == null) {
                            TreeSet<HotItem> set = new TreeSet<HotItem>(new Comparator<HotItem>() {
                                @Override
                                public int compare(HotItem o1, HotItem o2) {
                                    int i = o2.getCount().compareTo(o1.getCount());
                                    return i == 0 ? 1 : i;
                                }
                            });
                            top3Plus.update(set);
                            ctx.timerService().registerEventTimeTimer(value.getWindowEndTime() + 5000);
                        }
                        TreeSet<HotItem> set = top3Plus.value();
                        set.add(value);
                        if (set.size() == 4) {
                            set.pollLast();
                        }
                    }

                    @Override
                    public void onTimer(long timestamp,
                                        OnTimerContext ctx,
                                        Collector<String> out) throws Exception {
                        TreeSet<HotItem> set = top3Plus.value();
                        String msg = "------------\n";

                        for (HotItem hotItem : set) {
                            msg += hotItem;
                        }

                        out.collect(msg);

                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
